import sys, os, re, json
from torf import Torrent

def get_gid(torrent_path):
    gid_path = torrent_path + '.gid'
    if os.path.exists(gid_path):
        with open(gid_path, 'r') as f:
            gid = f.read()
            return gid
    else:
        return None

target = sys.argv[1]
not_downloaded = {}
for top, _, files in os.walk(target, topdown=True):
    for file in files:
        if len(re.findall(r".torrent$", file))>0:
            path = os.path.join(top,file)
            torrent = Torrent.read(path, validate=False)
            try:
                if len(torrent.files) > 1:
                    filename = torrent.name
                    filepath = os.path.join(top,filename)
                    torrent.verify_filesize(filepath)
                else:
                    filename = torrent.files[0]
                    filepath = os.path.join(top,filename)
                    torrent.verify_filesize(filepath)
            except Exception as e:
                obj = {'name': torrent.name}
                gid = get_gid(path)
                if gid:
                    obj['gid'] = gid
                not_downloaded[path] = obj

print(json.dumps(not_downloaded))
